<?php

namespace App\Http\Rest\Member\Resource;

use App\Foundation\PasswordHelper;
use Framework\Foundation\Config;
use Framework\Foundation\Database\FDB;
use Framework\Foundation\Request\ServerRequest;
use Framework\Foundation\Response\ResponseGen;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Cookie\SetCookie;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key;

class Token
{
    /**
     * @param array $restParams
     * @param $request ServerRequest
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Envms\FluentPDO\Exception
     */
    public function getList(array $restParams, ServerRequest $request)
    {
    }

    public function getInfo(array $restParams)
    {
    }

    /**
     * @param array $restParams
     * @param $request ServerRequest
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Envms\FluentPDO\Exception
     */
    public function add(array $restParams, ServerRequest $request)
    {
//        $cookies = $request->getCookieParams();

        $username = $request->getIn("username");
        $password = $request->getIn("password");
        $remember = $request->getIn('keep_sign_in');
        $jumpUrl = $request->getIn('jump_url', '/member/userinfo_detail.html');
        if (empty($jumpUrl)) {
            $jumpUrl = '/shop/index.html';
        }


        $ret = FDB::from('member')
//            ->where(['username' => $username])
            ->where('mobile', $username)
            ->fetch();
        if (empty($ret)) {
            return ResponseGen::error(400, "用户名或密码错误");
        }
        $pass = new PasswordHelper();
        $check = $pass->check($ret['password'], $password);
        if (!$check) {
            return ResponseGen::error(400, "用户名或密码错误");
        }
        $key = Config::instance()->get('member.jwt.key');
        $token = (new Builder())
            ->withClaim("uid", $ret['member_id'])
            ->expiresAt(time() + 86400 * 30)
            ->getToken(new Sha256(), new Key($key));
        $tokenString = $token->__toString();

        if (!empty($remember)) {
            $cookie = new SetCookie([
                'Name' => 'Authorization',
                'Value' => $token->__toString(),
                'Expires' => time() + 86400 * 30
            ]);
        } else {
            $cookie = new SetCookie(['Name' => 'Authorization', 'Value' => $token->__toString()]);
        }

        if ($request->isAjax()) {
            $response = ResponseGen::success([
                'token' => $token->__toString(),
                'info' => ['member_id' => $ret['member_id']],
                'jump_url' => $jumpUrl . '?code=' . $tokenString
            ]);
        } else {
            $response = ResponseGen::locationJump($jumpUrl . '?code=' . $tokenString);
        }
        $response = $response->withHeader('Set-Cookie', $cookie->__toString());

        return $response;
    }


    public function edit(array $restParams, $request)
    {
    }


    public function delete(array $restParams)
    {
        $response = ResponseGen::success();
        $cookie = new SetCookie(['Name' => 'Authorization', 'Value' => '']);
        return $response->withHeader('set-cookie', $cookie->__toString());
    }
}
